const { fork } = require('child_process');
let macroTasks = []; /** ←宏任务*/
let microTasks = []; /** ←微任务*/

class XMLHttpRequest {
  constructor() {
    this.options = {};
  }
  open(method, url) {
    this.options.method = method;
    this.options.url = url;
  }
  send() {
    let child = fork('./XMLHttpRequest.js');
    child.on('message', (message) => {
      if (message.type === 'response') {
        this.response = message.data;
        macroTasks.push(this.onload);
      }
    });
    child.send({ type: 'send', options: this.options });
  }
}
function fetchData() {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost:3000/data');
  xhr.onload = function () {
    console.log(xhr.response);
  };
  xhr.send();
}

class Promise {
  constructor(executor) {
    executor(this.resolve);
  }
  then = (onResolve) => {
    this._onResolve = onResolve;
  };
  resolve = (value) => {
    microTasks.push(() => this._onResolve(value));
  }
}

console.log(1);
fetchData();
console.log(2);
new Promise(function (resolve) {
  resolve('promise1');
}).then(result => console.log(result));
new Promise(function (resolve) {
  resolve('promise2');
}).then(result => console.log(result));
console.log('3');

setInterval(() => {
  let macroTask = macroTasks.shift();
  macroTask && macroTask();
  let microTask = microTasks.shift();
  while(microTask){
    microTask();
    microTask = microTasks.shift();
  }
}, 0);

